package tomoto.util;

/**
 * Holder to implement the copy-on-write memory management. This holder
 * automatically duplicates an object at the first time the client tries to
 * write to the object.
 * 
 * @author Tomoto Shimizu Washio
 * 
 * @param <T> Object type
 */
public class CowHolder<T extends Duplicatable<T>> {
	private T m_object;
	private boolean m_isCopied;
	
	public CowHolder(T object) {
		m_object = object;
		m_isCopied = false;
	}
	
	public T read() {
		return m_object;
	}
	
	public T write() {
		if (!m_isCopied) {
			m_object = m_object.dup();
			m_isCopied = true;
		} 
		return m_object;
	}
}
